
package com.scs.application.modules.settlement.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.google.common.collect.Lists;
import com.scs.application.core.exceptions.BusinessException;
import com.scs.application.core.export.ExportParamDto;
import com.scs.application.core.model.CommonResult;
import com.scs.application.core.service.BaseServiceImpl;
import com.scs.application.core.utils.BeanUtils;
import com.scs.application.core.utils.StringUtils;
import com.scs.application.core.utils.UserUtils;
import com.scs.application.modules.design.service.QueryGenerator;
import com.scs.application.modules.msg.service.PushedRecordService;
import com.scs.application.modules.settlement.dto.DeptOprtUseDTO;
import com.scs.application.modules.settlement.entity.DeptOprtUse;
import com.scs.application.modules.settlement.entity.DeptOprtUseItem;
import com.scs.application.modules.settlement.mapper.DeptOprtUseMapper;
import com.scs.application.modules.settlement.request.DeptOprtUseQueryRequest;
import com.scs.application.modules.settlement.service.DeptOprtUseItemService;
import com.scs.application.modules.settlement.service.DeptOprtUseService;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * 病人消耗主单 service 实现
 */
@Slf4j
@Service
@AllArgsConstructor
@Transactional(rollbackFor = Exception.class)
public class DeptOprtUseServiceImpl extends BaseServiceImpl<DeptOprtUseMapper, DeptOprtUse> implements DeptOprtUseService {


    private final DeptOprtUseItemService deptOprtUseItemService;
    private final PushedRecordService pushedRecordService;

    @Override
    public List<DeptOprtUse> list(DeptOprtUseQueryRequest request) {
        request.setSupplierId(UserUtils.getSupplierId());
        List<DeptOprtUse> list = this.baseMapper.listDeptOprtUse(request);
        return list;
    }

    @Override
    public IPage<DeptOprtUse> page(DeptOprtUseQueryRequest request) {
        request.setSupplierId(UserUtils.getSupplierId());
        IPage page = this.baseMapper.pageDeptOprtUse(request.getPage(), request);
        return page;
    }

    @Override
    public CommonResult receiveDeptOprtUse(List<DeptOprtUseDTO> deptOprtUseDTOs) {

        deptOprtUseDTOs.forEach(DeptOprtUseDTO -> {
            for (DeptOprtUseDTO.DeptOprtUseItemDTO itemDTO : DeptOprtUseDTO.getItems()) {
                if (StringUtils.isBlank(itemDTO.getMfgName())) {
                    itemDTO.setMfgName("默认厂商");
                }
                if (StringUtils.isBlank(itemDTO.getMatrSpec())) {
                    itemDTO.setMatrSpec("默认品规");
                }
            }
            DeptOprtUseDTO.setHospitalId(UserUtils.getHospitalId()).setHospitalName(UserUtils.getHospital().getName());
            // billDTO.setGmtBill(billDTO.getGmtCreate());
        });
        this.batchSaveForDTO(deptOprtUseDTOs);

        return CommonResult.ok("保存成功");
    }

    /**
     * 第三方病人消耗单接口批量保存病人消耗单
     */
    @Override
    public void batchSaveForDTO(List<DeptOprtUseDTO> deptOprtUseDTOS) {
        log.info("高值消耗接收 {}",deptOprtUseDTOS.size());
        //String hospitalId = UserUtils.getHospitalId();
//        String hospitalId = "1244433999238021122";
        Set<String> busKeyList = deptOprtUseDTOS.stream().map(DeptOprtUseDTO::getBusKey).collect(Collectors.toSet());
        List<String> busKeyListDb = this.list(Wrappers.<DeptOprtUse>query().select("bus_key").in("bus_key", busKeyList).eq("hospital_id", deptOprtUseDTOS.get(0).getHospitalId()))
                .stream().map(DeptOprtUse::getBusKey).collect(Collectors.toList());
        if (busKeyListDb == null) {
            busKeyListDb = Lists.newArrayList();
        }
        List<String> finalBusKeyListDb = busKeyListDb;
        List<DeptOprtUseDTO> dtos = deptOprtUseDTOS.stream().filter(tmp -> !finalBusKeyListDb.contains(tmp.getBusKey())).collect(Collectors.toList());
        // 保存操作
        if (dtos.isEmpty()) {
            return;
        }
        List<DeptOprtUse> list = Lists.newArrayListWithCapacity(dtos.size());
        BeanUtils.copyProperties(dtos, list, DeptOprtUse.class);
        // 保存病人消耗单主表
        saveBatch(list);

        Map<String, String> map = list.stream().collect(Collectors.toMap(o -> o.getBusKey(), o -> o.getId(), (o1, o2) -> o1));

        List<DeptOprtUseItem> itemList = new ArrayList<>();
        List<String> dtlIdList = Lists.newArrayList();
        for (DeptOprtUseDTO deptOprtUseDTO : dtos) {
            List<DeptOprtUseItem> tmpList = Lists.newArrayListWithExpectedSize(deptOprtUseDTO.getItems().size());
            BeanUtils.copyProperties(Lists.newArrayList(deptOprtUseDTO.getItems()), tmpList, DeptOprtUseItem.class);
            tmpList.stream().forEach(o -> {
                o.setDeptOprtUseId(map.get(deptOprtUseDTO.getBusKey()));
            });
            tmpList = tmpList.stream().filter(tmp ->  !dtlIdList.contains(tmp.getDtlId())).collect(Collectors.toList());
            if (tmpList.size() > 0) {
                itemList.addAll(tmpList);
                dtlIdList.addAll(tmpList.stream().map(DeptOprtUseItem::getDtlId).collect(Collectors.toList()));
            }
        }

        // 保存记账单明细表
        deptOprtUseItemService.saveBatch(itemList);

        pushedRecordService.pushVxBusCommonAsync(
                itemList.stream().map(DeptOprtUseItem::getSupplierId).distinct().collect(Collectors.toList()),
                list.get(0).getHospitalName(),
                "高值记账单推送成功",
                "oprt_use_index"
        );
    }


    private QueryWrapper<DeptOprtUse> getQueryWrapper(DeptOprtUseQueryRequest request) {
        return Wrappers.<DeptOprtUse>query()
                .eq(StringUtils.isNotBlank(request.getHospitalName()), "hospital_name", request.getHospitalName())
                .eq(StringUtils.isNotBlank(request.getBusKey()), "bus_key", request.getBusKey())
                .eq(StringUtils.isNotBlank(request.getOprtName()), "oprt_name", request.getOprtName())
                .orderByDesc("gmt_modified");
    }


    @Override
    public String exportFullData(QueryWrapper queryWrapper, ExportParamDto exportParams, Map<String, Object> userParam, HttpServletRequest request) {
        List result = null;
        if (exportParams.getIsAll()) {
            result = baseMapper.listSum(queryWrapper);
        } else{
            IPage  page = QueryGenerator.parsePage(request);
            result = baseMapper.pageSum(page,queryWrapper).getRecords();
        }

        try {
            String downloadPath = exportService.export(result, exportParams);
            return downloadPath;
        } catch (Exception e) {
            log.error("BaseServiceImpl.exportFullData", e);
            throw new BusinessException("文件生成失败，原因：" + e != null ? e.getMessage() : "未知异常");
        }
    }


    @Override
    public String exportFullDataByMatrName(QueryWrapper<DeptOprtUse> queryWrapper, ExportParamDto exportParams, Map<String, Object> userParam, HttpServletRequest request) {
        List result = null;
        if (exportParams.getIsAll()) {
            result = baseMapper.listSumByMatrName(queryWrapper);
        } else{
            IPage  page = QueryGenerator.parsePage(request);
            result = baseMapper.pageSumByMatrName(page,queryWrapper).getRecords();
        }

        try {
            String downloadPath = exportService.export(result, exportParams);
            return downloadPath;
        } catch (Exception e) {
            log.error("BaseServiceImpl.exportFullData", e);
            throw new BusinessException("文件生成失败，原因：" + e != null ? e.getMessage() : "未知异常");
        }
    }
}
